//@author A0087191Y
package net.mysoc.w111j.service.filters;

import static net.mysoc.w111j.ui.Constants.DATE_FORMAT;

import java.util.Date;

import net.mysoc.w111j.model.Expense;

/**
 * An {@code ExpenseFilter} matching expenses that occur in a given date range.
 */
public class DateExpenseFilter implements ExpenseFilter {
    private final Date start;
    private final Date end;

    public DateExpenseFilter(Date start, Date end) {
        if (start == null && end == null) {
            throw new NullPointerException("Start and end dates cannot be both null.");
        }
        if (start != null && end != null && start.compareTo(end) > 0) {
            throw new IllegalArgumentException("End date should be after or same start date");
        }
        this.start = start;
        this.end = end;
    }

    @Override
    public boolean shouldSelect(Expense expense) {
        boolean occursAfterStart = (start == null || start.compareTo(expense.getDate()) <= 0);
        boolean occursBeforeEnd = (end == null || end.compareTo(expense.getDate()) >= 0);
        return (occursAfterStart && occursBeforeEnd);
    }

    @Override
    public String getDescription() {
        if (start == null) {
            return "Before " + DATE_FORMAT.format(end);
        } else if (end == null) {
            return "Since " + DATE_FORMAT.format(start);
        } else {
            return DATE_FORMAT.format(start) + " – " + DATE_FORMAT.format(end);
        }
    }
}
